package utils

import (
	"encoding/json"
)

// MarshalJSON 将对象转换为JSON字符串
func MarshalJSON(v interface{}) (string, error) {
	bytes, err := json.Marshal(v)
	if err != nil {
		return "", err
	}
	return string(bytes), nil
}

// UnmarshalJSON 将JSON字符串转换为对象
func UnmarshalJSON(jsonStr string, v interface{}) error {
	return json.Unmarshal([]byte(jsonStr), v)
}

// SortByField 根据字段对切片进行排序
func SortByField(data []map[string]interface{}, field string, ascending bool) {
	// 根据字段排序
	for i := 0; i < len(data)-1; i++ {
		for j := i + 1; j < len(data); j++ {
			// 获取字段值进行比较
			iValue, iOk := data[i][field]
			jValue, jOk := data[j][field]
			
			if !iOk || !jOk {
				continue
			}
			
			// 比较数字类型
			switch iVal := iValue.(type) {
			case float64:
				if jVal, ok := jValue.(float64); ok {
					if (ascending && iVal > jVal) || (!ascending && iVal < jVal) {
						data[i], data[j] = data[j], data[i]
					}
				}
			case int:
				if jVal, ok := jValue.(int); ok {
					if (ascending && iVal > jVal) || (!ascending && iVal < jVal) {
						data[i], data[j] = data[j], data[i]
					}
				}
			case string:
				if jVal, ok := jValue.(string); ok {
					if (ascending && iVal > jVal) || (!ascending && iVal < jVal) {
						data[i], data[j] = data[j], data[i]
					}
				}
			}
		}
	}
} 